package com.hunttown.mes.common.utils;

import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * created by wangjunfu on 2018/5/25
 */
public class DateUtils {

    //两个时间之间相差距离多少天，有正负之分
    public static long getDistanceDaysSymbol(String date1, String date2) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date one;
        Date two;
        long days = 0;
        try {
            one = df.parse(date1);
            two = df.parse(date2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            long symbol = 1;
            if (time1 < time2) {
                symbol = -1;
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            days = diff / (1000 * 60 * 60 * 24);
            days = symbol * days;

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }

    /**
     * 两个时间之间相差距离多少天
     *
     * @param date1 时间参数 1：
     * @param date2 时间参数 2：
     * @return 相差天数
     */
    public static long getDistanceDays(String date1, String date2) {
        long days = getDistanceDaysSymbol(date1, date2);
        return Math.abs(days);
    }

    /**
     * 两个时间之间相差距离多少天
     *
     * @param date1 时间参数 1：
     * @param date2 时间参数 2：
     * @return 相差天数
     */
    public static long getDistanceDays(Date date1, Date date2) {

        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long diff;
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        return diff / (1000 * 60 * 60 * 24);
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     *
     * @param date1 时间参数 1 格式：1990-01-01 12:00:00
     * @param date2 时间参数 2 格式：2009-01-01 12:00:00
     * @return long[] 返回值为：{天, 时, 分, 秒}
     */
    private static long[] getDistanceTimes(String date1, String date2) {
        date1 = DateConvertUtils.complementDate(date1);
        date2 = DateConvertUtils.complementDate(date2);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(date1);
            two = df.parse(date2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new long[]{day, hour, min, sec};
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     *
     * @param date1 时间参数 1 格式：1990-01-01 12:00:00
     * @param date2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public static String getDistanceTime(String date1, String date2) {
        long[] times = getDistanceTimes(date1, date2);
        return times[0] + "天" + times[1] + "小时" + times[2] + "分" + times[3] + "秒";
    }

    public static String getDistanceTime2(String date1, String date2) {
        long[] times = getDistanceTimes(date1, date2);

        String time = "";
        if (times[0] > 0L) {
            time += times[0] + "天";
        }
        if (times[1] > 0L) {
            time += times[1] + "小时";
        }
        if (times[2] > 0L) {
            time += times[2] + "分";
        }
        return time;
    }

    /**
     * 两个时间相差多少秒
     *
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return 秒
     */
    public static Long getDistanceSeconds(String str1, String str2) {
        str1 = DateConvertUtils.complementDate(str1);
        str2 = DateConvertUtils.complementDate(str2);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;

        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }

            return diff / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0L;
    }

    //两个时间相差多少分
    public static Long getDistanceMinutes(String str1, String str2) {
        if (str1.equals("1990-01-01 00:00:00") || str2.equals("1990-01-01 00:00:00")) {
            return 0L;
        }

        Long seconds = getDistanceSeconds(str1, str2);
        if (seconds <= 0) {
            return seconds;
        }

        if (seconds < 60) {
            return 1L;
        }

        return seconds / 60;
    }

    //两个时间相差多少小时
    public static Long getDistanceHour(String str1, String str2) {
        long minutes = getDistanceMinutes(str1, str2);

        if (minutes <= 60) {
            return 1L;
        }

        return minutes / 60;
    }

    /**
     * 格式化日期为：yyyy-MM-dd HH:mm:ss
     *
     * @param dateStr
     * @return
     */
    public static String formatDate(String dateStr) {

        if (StringUtils.isBlank(dateStr)) {
            // 空判断
            dateStr = "1990-01-01 00:00:00";
        } else {
            // 把 2018/10/1 0:00:00 日期转成 2018-10-1 0:00:00
            dateStr = dateStr.replaceAll("/", "-");
        }

        if (dateStr.length() == 10) {
            // 说明是短日期
            dateStr = String.format("%s 00:00:00", dateStr);
        }

        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt = format.parse(dateStr);
            dateStr = format.format(dt);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return dateStr;
    }

    /**
     * 判断日期为空的话 返回默认日期
     *
     * @param dateStr
     * @return
     */
    public static String judgeIsNullOrEmptyDate(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        if (StringUtils.isBlank(dateStr)) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(1970, Calendar.JANUARY, 1, 0, 0, 0);
            dateStr = format.format(calendar.getTime());
        }

        return dateStr;
    }

    /**
     * 比较两个日期大小
     *
     * @param beginTime
     * @param endTime
     * @return 正值 表是 beginTime 日期大
     */
    public static Integer compareDate(String beginTime, String endTime) {
        return beginTime.compareTo(endTime);
    }

    /**
     * 比较两个日期大小
     *
     * @param beginTime
     * @param endTime
     * @return true表示前面的日期小
     */
    public static Boolean compareDateTime(String beginTime, String endTime) {
        try {
            beginTime = DateConvertUtils.complementDate(beginTime);
            endTime = DateConvertUtils.complementDate(endTime);

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d1 = df.parse(beginTime);
            Date d2 = df.parse(endTime);
            return d1.before(d2);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 比较两个日期是否相等，不包括秒
     *
     * @param beginTime 日期1
     * @param endTime   日期2
     * @return true相等
     */
    public static Boolean compareDateEqual(String beginTime, String endTime) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date d1 = df.parse(beginTime);
            Date d2 = df.parse(endTime);
            return d1.equals(d2);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 比较两个日期大小
     *
     * @param beginTime
     * @param endTime
     * @return true表示前面的日期小
     */
    public static Boolean compareShortDate(String beginTime, String endTime) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date d1 = df.parse(beginTime);
            Date d2 = df.parse(endTime);
            return d1.before(d2);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 比较两个时间大小
     *
     * @param beginTime
     * @param endTime
     * @return true表示前面的时间小
     */
    public static Boolean compareTime(String beginTime, String endTime) {
        try {
            String[] arrBegin = beginTime.split(" ");
            String[] arrEnd = endTime.split(" ");

            String newBegin = "2022-11-16 " + arrBegin[arrBegin.length - 1];
            String newEnd = "2022-11-16 " + arrEnd[arrEnd.length - 1];

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date beginDate = format.parse(newBegin);
            Date endDate = format.parse(newEnd);

            return beginDate.before(endDate);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取今年年份
     *
     * @return 年
     */
    public static Integer getCurrYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 获取本月月份
     *
     * @return 月
     */
    public static Integer getCurrMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取年月
     *
     * @return 例：2022-07
     */
    public static String getCurrYearMonth() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        return year + "-" + com.hunttown.mes.common.utils.StringUtils.padLeft(month, 2);
    }

    /**
     * 获取今天是几号
     *
     * @return 号
     */
    public static Integer getCurrDay() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取现在的小时
     *
     * @return hour
     */
    public static Integer getCurrHour() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取现在的分
     *
     * @return minute
     */
    public static Integer getCurrMinute() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MINUTE);
    }

    /**
     * 获取现在是当年第几周
     *
     * @return 第几周
     */
    public static Integer getCurrWeeks() {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        return calendar.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 获取当前时间的字符串
     *
     * @return 当前时间
     */
    public static String getCurrTimeSr() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }

    /**
     * 获取指定日期 年
     *
     * @param date 日期
     * @return 年
     */
    public static Integer getDateYear(Date date) {
        String year = String.format("%tY", date);
        return Integer.valueOf(year);
    }

    /**
     * 获取指定日期 月
     *
     * @param date 日期
     * @return 月
     */
    public static Integer getDateMonth(Date date) {
        String mon = String.format("%tm", date);
        return Integer.valueOf(mon);
    }

    /**
     * 获取指定日期 日
     *
     * @param date 日期
     * @return 日
     */
    public static Integer getDateDay(Date date) {
        String day = String.format("%td", date);
        return Integer.valueOf(day);
    }

    /**
     * 获取现在是当年第几周
     *
     * @param date 日期
     * @return 第几周
     */
    public static Integer getDateWeeks(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        return calendar.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 获取指定时间 小时
     *
     * @param date 时间
     * @return 时
     */
    public static String getDateHour(String date) {

        SimpleDateFormat format = new SimpleDateFormat("HH");
        String hour = null;
        try {
            Date dt = DateConvertUtils.strToDate(date);
            hour = format.format(new Date(dt.getTime()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hour;
    }

    //取出日期中的月份，并转化为：一月、二月......
    public static String getConvertMonth(Date date) {
        Integer mon = getDateMonth(date);

        String month = "";

        switch (mon) {
            case 1:
                month = "一月";
                break;
            case 2:
                month = "二月";
                break;
            case 3:
                month = "三月";
                break;
            case 4:
                month = "四月";
                break;
            case 5:
                month = "五月";
                break;
            case 6:
                month = "六月";
                break;
            case 7:
                month = "七月";
                break;
            case 8:
                month = "八月";
                break;
            case 9:
                month = "九月";
                break;
            case 10:
                month = "十月";
                break;
            case 11:
                month = "十一月";
                break;
            case 12:
                month = "十二月";
                break;
        }

        return month;
    }

    /**
     * 获取上个月的今天
     *
     * @return date
     */
    public static Date getLastMonthToday() {
        Date date = new Date();
        return getLastMonthToday(date);
    }

    /**
     * 获取上个月的今天
     *
     * @param date 指定日期
     * @return date
     */
    public static Date getLastMonthToday(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); //设置为上一个月
        date = calendar.getTime();
        return date;
    }

    //获取时间戳（毫秒级）
    public static long getTimestamp() {
        return System.currentTimeMillis();
    }

    //时间戳转化为日期
    public static String timestampToDate(long timestamp) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(new Date(Long.parseLong(String.valueOf(timestamp)) * 1000L));
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 生成 “年-月-日” 日期序列
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 日期列表
     */
    public static List<String> getDayList(String startDate, String endDate) {
        String pattern = "yyyy-MM-dd";
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);

        // 生成年月日的日期序列
        List<String> res = new ArrayList<>();

        // 这里先对startDate减一天，最后的结果才能包含startDate
        LocalDate newStartDate = LocalDate.parse(startDate, dateFormat).minusDays(1);
        LocalDate newEndDate = LocalDate.parse(endDate, dateFormat);

        while (!newStartDate.equals(newEndDate)) {
            newStartDate = newStartDate.plusDays(1);
            String dateString = dateFormat.format(newStartDate);
            res.add(dateString);
        }
        return res;
    }

    /**
     * 生成 “年-月-日” 日期序列
     *
     * @param startDate 开始日期
     * @param gap       长度
     * @return 日期列表
     */
    public static List<String> getDayList(String startDate, int gap) {
        String pattern = "yyyy-MM-dd";
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);

        // 生成年月日的日期序列
        List<String> res = new ArrayList<>();
        for (int i = 0; i < gap; i++) {
            LocalDate newDate = LocalDate.parse(startDate, dateFormat).plusDays(i);
            String dateString = dateFormat.format(newDate);
            res.add(dateString);
        }
        return res;
    }

    /**
     * 生成 “年-月-日” 日期序列
     *
     * @param gap     长度
     * @param endDate 结束日期
     * @return 日期列表
     */
    public static List<String> getDayList(int gap, String endDate) {
        String pattern = "yyyy-MM-dd";
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);

        // 生成年月日的日期序列
        List<String> res = new ArrayList<>();
        for (int i = gap - 1; i >= 0; i--) {
            LocalDate newDate = LocalDate.parse(endDate, dateFormat).minusDays(i);
            String dateString = dateFormat.format(newDate);
            res.add(dateString);
        }
        return res;
    }

    /**
     * 生成 “年-月” 日期序列
     *
     * @param gap     长度
     * @param endDate 结束日期
     * @return 日期列表
     */
    public static List<String> getMonthList(int gap, String endDate) {
        String pattern = "yyyy-MM-dd";
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);

        String pat = "yyyy-MM";
        DateTimeFormatter format = DateTimeFormatter.ofPattern(pat);

        // 生成年月日的日期序列
        List<String> res = new ArrayList<>();
        for (int i = gap - 1; i >= 0; i--) {
            LocalDate newDate = LocalDate.parse(endDate, dateFormat).minusMonths(i);
            String dateString = format.format(newDate);
            res.add(dateString);
        }
        return res;
    }

    public static void main(String[] args) {
        //String dateSr1 = "2019-10-07";
        //String dateSr2 = "2019-10-08";

        //System.out.println(compareDate(dateSr1, dateSr2));
        //System.out.println(getDistanceDays(dateSr1, dateSr2));
        //System.out.println(compareDateTime(dateSr1, dateSr2));
        //System.out.println(getDistanceMinutes("2021-06-29 11:17", "2021-06-29 23:59"));

        //System.out.println("周1：" + getCurrWeeks());
        //System.out.println("周2：" + getDateWeeks("2022-02-16 10:02:36"));

        //String date = timestampToDate(1652966650);
        //System.out.println("转完的日期：" + date);

        //List<String> dayList = getDayList("2022-06-25", "2022-07-06");
        //System.out.println(String.join(",", dayList));

        //List<String> monthList = getMonthList(12, "2022-07-27");
        //System.out.println(String.join(",", monthList));

        int year = DateUtils.getCurrYear();
        int month = DateUtils.getCurrMonth();
        System.out.println("年月：" + year + "-" + month);

    }
}
